package com.csaba.connector.otp.parser;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.Source;
import net.htmlparser.jericho.TextExtractor;

public class LoginParser
{
	//private final static Logger logger = LoggerHelper.getDefaultLogger();

	private static final Pattern ERROR_INDICATOR_SMSLOGIN = Pattern.compile("<div[^>]*hibak.*>");
	private static final String SMS_INDICATOR_ERROR = "smsAzonosito";

	//Error patterns:
	//errors on the page: (table areas, td hasab_23 , this is the only <h2/> element on the page.
	// - invalid input: <h2 align="left" style="color: #a80927;">Hiba a bevitt adatokban!</h2>
	//		<p align="justify" class="utolso">Sajnáljuk, de az Ön által megadott számlaszám formátuma hibás.</p>
	// - blocked account: <h2 align="left" style="color: #a80927;">Letiltva!</h2>
	//		<p align="justify">Az Ön Azonosítója felfüggesztésre került. </p>

	public static String parseLoginError( final Source source ) throws IOException, ParseException
	{
		final StringBuilder message = new StringBuilder();
		// find the account table
		final Element h2 = source.getNextElement(0, "h4");
		if ( h2 != null )
		{
			message.append(new TextExtractor(h2).toString());

			final Element p = source.getNextElement(h2.getEnd(), "p");
			if ( p != null )
			{
				message.append(" ");
				message.append(new TextExtractor(p).toString());
			}
		}

		if ( message.length() == 0 )
		{
			message.append("Unable to parse error message.");
		}

		return message.toString();
	}

	public static boolean isErrorOccured( final Source source )
	{
		final Element title = source.getFirstElement("title");
		if ( title != null )
		{
			final String titleText = new TextExtractor(title).toString();
			if ( titleText.contains("hiba") || titleText.contains("Hiba") )
				return true;
		}
		return false;
	}

	public static boolean isErrorOccuredSMSLogin( final String result )
	{
		final Matcher matcher = ERROR_INDICATOR_SMSLOGIN.matcher(result);
		return matcher.find();
	}

	public static boolean isSMSLogin( final String result )
	{
		return result.contains(SMS_INDICATOR_ERROR);
	}

	public static String extractProfileURL( final String result )
	{
		//		ajaxTest('/homebank/do/profile;jsessionid=v1hFNynThJTKG0PTMzRJ68DP06nBlRLx4Xlqv1x47mhJCGZ2pTWJ!604835461!webapp2!17013!-1!582360980!webapp1!17013!-1');
		final int ajaxTestIndex = result.indexOf("ajaxTest");
		if ( ajaxTestIndex < 0 )
			return null;

		final int openning = result.indexOf('\'', ajaxTestIndex);
		if ( openning < 0 )
			return null;

		final int closing = result.indexOf('\'', openning + 1);
		if ( closing < 0 )
			return null;

		return result.substring(openning + 1, closing);
	}

	public static String parseSMSLoginError( final Source source ) throws IOException
	{
		//note: UTF8 characters are replaced below
		//        <div class="hibak" id="result_message">
		//        <h3>Hiba a tranzakcio feldolgozasa kozben.</h3>
		//        <!-- hibauzenetek -->
		//        <ul><li>Nem talalhato a megadott azonositoval rendelkezo tranzakcio. Kerjuk ellenorizze a beirt adatokat!</li></ul>
		//        <!-- end hibauzenetek -->
		//    </div>

		String message = null;
		// find the account table
		final Element div = source.getFirstElementByClass("hibak");

		if ( div != null )
		{
			message = new TextExtractor(div).toString();
		}

		if ( message == null || message.length() == 0 )
		{
			message = "Unable to parse error message.";
		}

		return message;
	}

	public static String parseCustomerName( final Source source ) throws IOException
	{
		//extract user name here
		//<div id="userinfo"><h2>Üdvözöljük <strong>USER NAME</strong></h2></div>

		String message = null;
		// find the account table
		final Element div = source.getElementById("userinfo");

		if ( div != null )
		{
			final Element strong = source.getNextElement(div.getStartTag().getEnd(), "strong");
			if ( strong != null )
				message = new TextExtractor(strong).toString();
		}

		if ( message == null || message.length() == 0 )
		{
			message = "<Invalid User Namey>";
		}

		return message;
	}

	public static void main( final String[] args ) throws Exception
	{
		/*
		final Source source = new Source(new InputStreamReader(new FileInputStream(args[0])));
		System.out.println(new TextExtractor(source).toString());
		*/
		/*
		final BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(args[0])));
		final StringBuilder builder = new StringBuilder();
		String line = reader.readLine();
		while ( line != null )
		{
			builder.append(line).append("\n");
			line = reader.readLine();
		}
		reader.close();

		System.out.println(args[0] + " : " + isErrorOccuredSMSLogin(builder.toString()));
		*/
		final BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(
				"../otp.source/smshiba.html")));
		System.out.println("Error: " + parseSMSLoginError(new Source(reader)));
	}

}
